# -*- coding: utf-8 -*-

# $Id: model.py 2 2012-09-01 15:54:17Z alexis.roda.villalonga@gmail.com $

from dja_skel.lib import utils
from dja_skel.skeletons.base import BaseModelSkel


class ModelSkel(BaseModelSkel):
    variables = ("applabel", "ModelName")
    skeleton_path = "templates/model"
    summary = "Creates a model and a model admin"

    def after_instantiation(self):
        super(ModelSkel, self).after_instantiation()
        self._add_model_package_imports()
        self._add_admin_boilerplate()
        self._add_permissions()

    def _add_model_package_imports(self):
        """Adds an import for the model to the packages's __init__.py.
        """
        init = self.app.get_file(
            "models/__init__.py",
            encoding=self._encoding
            )
        import_ = "from {applabel}.models.{model_name} import {ModelName}\n".format(
            applabel=self._context["applabel"],
            model_name=self._context["model_name"],
            ModelName=self._context["ModelName"]
            )
        init.insert_before([import_], "MODEL IMPORTS")
        init.save()

    def _add_admin_boilerplate(self):
        """Adds an import for the model_admin to the packages's
        __init__.py and registers it with the admin.
        """
        init = self.app.get_file(
            "admin/__init__.py",
            encoding=self._encoding
            )
        import_ = "from {applabel}.admin.{model_name} import {ModelName}Admin\n".format(
            applabel=self._context["applabel"],
            model_name=self._context["model_name"],
            ModelName=self._context["ModelName"]
            )
        init.insert_before([import_], "MODELADMIN IMPORTS")

        registration = "admin.site.register(models.{ModelName}, {ModelName}Admin)\n".format(
            ModelName=self._context["ModelName"]
            )
        init.insert_before([registration], "MODELADMIN REGISTRATION")
        init.save()

    def _add_permissions(self):
        permissions = self.app.get_file(
            "permissions.py",
            encoding=self._encoding
            )
        lines = []
        lines.append("# permissions for {ModelName}\n".format(
            ModelName=self._context["ModelName"]
        ))
        for perm in ("add", "change", "delete", "read"):
            lines.append('{model_name}_{perm} = "{applabel}.{perm}_{modelname}"\n'.format(
                perm=perm,
                applabel=self._context["applabel"],
                model_name=self._context["model_name"],
                modelname=self._context["modelname"]
            ))
        lines.append("\n")
        permissions.insert_before(lines, "MODEL PERMISSIONS")
        permissions.save()
